package cn.imvc.app.controllers.system;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import cn.imvc.app.entities.Group;
import cn.imvc.app.entities.Role;
import cn.imvc.app.entities.User;
import cn.imvc.app.models.MenuModel;
import cn.imvc.app.models.UserModel;
import cn.imvc.core.HttpContext;

public class IndexControllerImpl implements IndexController{

	public String  navMenu;
	public String  menuTree;
	public String defaultMenu;
	public int id;
	
	public void setId(int id) {
		this.id = id;
	}

	@Autowired
	private MenuModel menuModel;
	@Autowired
	private UserModel userModel;

	public String index() {
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String username="";
		if (principal instanceof UserDetails) {
		   username = ((UserDetails)principal).getUsername();
		} else {
		   username = principal.toString();
		}
		User user=userModel.get(username);
		Set<Role> roles=new HashSet<Role>();
		roles.addAll(user.getRole());
		for (Object object : user.getGroup()) {
			Group group=(Group)object;
			roles.addAll(group.getRole());
		}
		HttpContext.getSession().setAttribute("userRole", roles);
		navMenu=menuModel.getNavMenu();
		defaultMenu=menuModel.getDefaultMenu(roles);
		return "index/index";
	}

	public String show() {
		Set<Role> roles =(Set<Role>)HttpContext.getSession().getAttribute("userRole");
		menuTree=menuModel.getMenus(id,roles);
		return "index/show";
	}


}
